<?php
/**
 * 权益业务层
 * User: Acer
 * Date: 2022/7/10
 * Time: 1:14
 */
namespace app\move\service;



use app\card\models\CardModel;
use app\card\models\CardProModel;
use app\card\models\UserCardModel;
use app\card\service\CardProService;
use app\card\service\CardService;
use app\card\service\CardTypeService;
use app\move\models\CardEquityModel;
use app\move\models\CardEquityUserModel;
use app\move\models\CardEquityUserInfoModel;
use app\move\models\FamilyCardModel;
use app\move\models\IdentityCardModel;
use app\move\models\CardUserModel;
use app\admin\models\AreaRegionModel;
use app\admin\models\HospitalModel;
use app\admin\models\Hospital2Model;
use think\Log;

class EquityService {

    /**
     * 获取当前用户的权益列表[主卡]
     * joker
     * @param $page
     * @param int $paginate
     * @param $like
     * @param null $uid
     * @param int $type
     */
    public function s_get_list($page,$paginate=10,$like=[],$uid = null,$type =2){
        // 获取绑定列表
        $UserCardModel =new UserCardModel();
        $UserCardModel->where('uid',$uid)->where('is_other','NULL')->where('parent_cu_id', 'NULL');
        if($type == 2){ // 激活
            $UserCardModel->where('is_active',1);
        }elseif($type == 3){ // 失效
            $UserCardModel->where('is_active',2);
        }

        // 持卡人
        $IdentityCardModel = new IdentityCardModel();
        $IdentityCardInfo = $IdentityCardModel->where('uid', $uid)->find();
        $IdentityCardInfo = obj_to_arr($IdentityCardInfo);

        $list = $UserCardModel->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key) use ($IdentityCardInfo) {
            // 获取卡片产品信息
            $card_pro_info = (new CardProService())->m_card_pro_info($item['pid']);
            $card_pro_info = obj_to_arr($card_pro_info);
            $item['card_pro_info'] = $card_pro_info;
            // 获取卡片信息
            $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
            $card_info = obj_to_arr($card_info);
            $item['card_info'] = $card_info;
            // 获取卡片类型
            $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
            $card_type = obj_to_arr($card_type);
            $item['card_type'] = $card_type;
            // 持卡人
            $item['identity_card_info'] = $IdentityCardInfo;
            // 叠加卡
            $item['append'] = [];
            if($card_type['id']==17){
                $append = obj_to_arr((new UserCardModel())
                    ->where('cu_id', $item['cu_id'])
                    ->whereOr('parent_cu_id', $item['cu_id'])
                    ->order('valid_time', 'asc')->select());
                foreach ($append as &$subItem){
                    $subItem['code']=(new CardProModel())->where('pid',$subItem['pid'])->value('code');
                    $subItem['name']=$IdentityCardInfo['name'];
                }
                $item['append'] = $append;
            }
        });
        $list = obj_to_arr($list);
        return $list;
    }

    /**
     * 获取当前用户的权益列表[成员卡]
     * @param $page
     * @param int $paginate
     * @param array $like
     * @param null $uid
     * @param int $type
     * @return mixed
     */
    public function s_fit_get_list($page,$paginate=10,$like=[],$uid = null,$type =1){
        $UserCardModel = new UserCardModel();
        // 获取绑定列表
        $FamilyCardModel = new FamilyCardModel();
        // 用户身份证信息
        $IdentityCardModel= new IdentityCardModel();
        $did = $IdentityCardModel->where('uid',$uid)->value('did');
        $returnData = [
            'total'         =>  0,
            'per_page'      =>  $paginate,
            'current_page'  =>  0,
            'last_page'     =>  0,
            'data'          =>  []
        ];
        if(!$did) return $returnData;

//        // 开启的上级id，获取主卡信息
//        $puidInfo = $FamilyCardModel->where('did',$did)->where('state',1)->select();
//        $puidInfo = obj_to_arr($puidInfo);
//        if(!$puidInfo) return $returnData;
//        $keypid = implode(',',array_filter(array_column($puidInfo, 'pid')));
//        if(!$keypid)  return $returnData;
//        $UserCardModel->where('pid','in',$keypid)->where('is_active','<',time());

        $list = $UserCardModel->alias("uc")
            ->join("family_card fc", "uc.pid=fc.pid")
            ->field("uc.*,fc.puid")
            ->where(["fc.did"=>$did,"fc.state"=>1])
            ->where('uc.is_active',1)
            ->where('uc.parent_cu_id', 'NULL')
            ->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
//        $list = $UserCardModel->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
                // 获取卡片产品信息
                $card_pro_info = (new CardProService())->m_card_pro_info($item['pid']);
                $card_pro_info = obj_to_arr($card_pro_info);
                $item['card_pro_info'] = $card_pro_info;
                // 获取卡片信息
                $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
                $card_info = obj_to_arr($card_info);
                $item['card_info'] = $card_info;
                // 获取卡片类型
                $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
                $card_type = obj_to_arr($card_type);
                $item['card_type'] = $card_type;
                // 持卡人
                $IdentityCardModel = (new IdentityCardModel())->where('uid',$item['puid'])->find();
                $IdentityCardModel = obj_to_arr($IdentityCardModel);
                $item['identity_card_info'] = $IdentityCardModel;
                // 叠加卡
                $item['append'] = [];
                if($card_type['id']==17){
                    $append = obj_to_arr((new UserCardModel())
                        ->where('cu_id', $item['cu_id'])
                        ->whereOr('parent_cu_id', $item['cu_id'])
                        ->order('valid_time', 'asc')->select());
                    foreach ($append as &$subItem){
                        $subItem['code']=(new CardProModel())->where('pid',$subItem['pid'])->value('code');
                        $subItem['name']=$IdentityCardModel['name'];
                    }
                    $item['append'] = $append;
                }
        });
        return obj_to_arr($list);
    }

    // 获取卡片产品权益详情
    public function s_card_pro_info($pid,$uid){
        // 获取卡片产品信息
        $card_pro_info = (new CardProService())->m_card_pro_info($pid);
        $card_pro_info = obj_to_arr($card_pro_info);
        if(!$card_pro_info) json_err(-204,['卡片产品信息,']);
        // 获取卡片信息
        $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
        $card_info = obj_to_arr($card_info);
        if(!$card_info) json_err(-204,['卡片信息,']);
        // 获取卡片类型
        $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
        $card_type = obj_to_arr($card_type);
        if(!$card_type) json_err(-204,['卡片类型信息,']);
        // 获取当前认证信息
        $IdentityCardModel = new IdentityCardModel();
        $IdentityCardInfo = $IdentityCardModel->where('uid',$uid)->find();
        $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
        if(!$IdentityCardInfo) json_err(-201,['该用户信息未认证！']);
        // 查看是否是家庭成员卡
        $bind_family_card_info = (new CardUserService())->s_bind_family_card_info($pid,$IdentityCardInfo['did']);
        $bind_family_card_info =obj_to_arr($bind_family_card_info);
        // 查看是否是代替激活的卡
        $bind_agent_card_info= (new CardUserService())->s_bind_agent_card_info($pid,$uid);
        $data =[
            'is_master'    => 0, // 1:主卡本人 0：不是主卡本人，成员卡
            'f_user_uid'     => null, // 家庭成员ID
            'is_add_user'    => 0,      // 是否可以添加用户（0：否、1：是）
            'add_user_invalid_time'   => time(),  // 失效时间
            'identity_card_info' => $IdentityCardInfo, // 持卡人信息
        ];
        if($bind_family_card_info){
            // 获取卡片绑定信息
            $bind_card_info = (new CardUserService())->s_bind_card_info($pid,$bind_family_card_info['puid']);
            $data['f_user_uid'] = $IdentityCardInfo['uid'];
            $IdentityCardInfo = $IdentityCardModel->where('uid',$bind_family_card_info['puid'])->find();
            $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
            $data['identity_card_info'] = $IdentityCardInfo;
        }else if($bind_agent_card_info){
            $IdentityCardInfo = $IdentityCardModel->where('did', $bind_agent_card_info['did'])->find();
            $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
            $data['agent_user_uid'] = $IdentityCardInfo['uid'];
            $bind_card_info = (new CardUserService())->s_bind_card_info($pid,$uid);
            $data['is_master'] = 3;
            $data['identity_card_info'] = $IdentityCardInfo;
        }else{
            // 获取卡片绑定信息
            $bind_card_info = (new CardUserService())->s_bind_card_info($pid,$uid);
            $data['is_master'] = 1;
        }
        $bind_card_info = obj_to_arr($bind_card_info);
        if(!$bind_card_info) json_err(-204,['卡片产品绑定信息,']);
        // 根据卡片获取当前使用中的权益
        if(!$card_info['eid']) json_err(-210,['卡片无权益信息']);
        $eids =explode(',', $card_info['eid']);
        $equityInfo = (new CardEquityModel())->where('state',1)->where('eid','in',$eids)->select();
        $equityInfo = obj_to_arr($equityInfo);

        foreach($equityInfo as $key=>$value){

            // 用户权益实际是否使用完毕
            $cardEquityUserData = obj_to_arr((new CardEquityUserModel())->where([
                'cu_id' => $bind_card_info['cu_id'],
                'cid'   => $card_info['cid'],
                'uid'   => (isset($data['agent_user_uid'])&& !empty($data['agent_user_uid']))?$data['agent_user_uid']:$uid,
                'eid'   => $value['eid'],
                'state'  =>  [ [ 'neq' , 2] , [ 'NULL', '' ] , 'or' ],
            ])->select());

            $count = count($cardEquityUserData);
            $equityInfo[$key]['new_frequency'] = $count; // 当前使用次数
            $frequency = (int)$value['frequency'];
            // 住院协助&出院协助是每个权益人都可以一年使用一次
            // 45: 住院协助（1次/年）, 48: 出院协助（1次/年）
            $eid = (int)$value['eid'];
            if($eid == 45 or $eid == 48){
                $frequency = $frequency * ((new FamilyCardModel())->where(['pid'=>$pid,'puid'=>$uid])->count() || 1);
                $equityInfo[$key]['card_equity_user_list'] = $cardEquityUserData;
            }
            if($frequency > $count){
                $equityInfo[$key]['is_overdue'] = 0; // 次数未使用完毕
            }else{
                $equityInfo[$key]['is_overdue'] = 1; // 次数使用完毕
            }
            if($equityInfo[$key]['waiting_period'] > 0){ // 等待期
                $addDays = sprintf("+%d day", $equityInfo[$key]['waiting_period']);
                $creationTime = strtotime($bind_card_info['creation_time']);
                $lastWaitingTime = strtotime(date("Y-m-d",strtotime($addDays, $creationTime)));
                $equityInfo[$key]['waiting_period'] = $lastWaitingTime;
            }else{
                $equityInfo[$key]['waiting_period'] = 0;
            }
        }

        // 权益按照卡片权益字段设置的顺序排列
        $tmp1 = [];
        foreach($equityInfo as $equity) {
            $tmp1[$equity['eid']]=$equity;
        }
        $tmp2 = [];
        foreach ($eids as $eid) {
            if(isset($tmp1[$eid])){
                $tmp2[] = $tmp1[$eid];
            }
        }
        $data['equity_list'] = $tmp2;

        // 查看是否可以添加关联用户
        if($card_type['people'] > 0 ){
            // 判断这个卡激活时间 + 家庭卡添加人员时间有效期，是否已过期
            $creation_time = strtotime($bind_card_info['creation_time']);
            $dayTime = config('family_card_add_user_time') * 24 * 3600;  // 有限期天数
            if($card_type['family_card_add_user_time']){
                $dayTime = $card_type['family_card_add_user_time'] * 24 * 3600;  // 有限期天数
            }
            $total_time = $creation_time + $dayTime; // 有限期时间戳
            $data['people'] = $card_type['people']; // 总共可添加人数
            $data['add_user_invalid_time'] = $total_time;
            // 判断当前添加用户数是否已经超标，超标则，不允许再添加
            $familyUserConut = (new FamilyCardModel())->where(['pid'=>$pid,'puid'=>$uid])->count();
            $data['new_people'] = $familyUserConut; // 现有添加人数
            $data['family_user'] = obj_to_arr((new FamilyCardModel())->where(['pid'=>$pid,'puid'=>$uid])->select());
            if($familyUserConut < (int)$card_type['people'] && time() < $total_time)  $data['is_add_user'] = 1;
        }
        // 安护无忧卡，叠加有效期默认30天
        if($card_type['id']==17){
            $append = obj_to_arr((new UserCardModel())
                ->where('cu_id', $bind_card_info['cu_id'])
                ->whereOr('parent_cu_id', $bind_card_info['cu_id'])
                ->order('valid_time', 'asc')->limit(1)->find());

            $creation_time = strtotime($append['creation_time']);
            $dayTime = 0;
            if($card_type['family_card_add_user_time']){
                $dayTime = $card_type['family_card_add_user_time'] * 24 * 3600;  // 有限期天数
            }
            $total_time = $creation_time + $dayTime; // 有限期时间戳
            $data['add_user_invalid_time'] = $total_time;
        }
        return $data;
    }

    //代替他人激活的卡片列表
 public function s_agent_get_list($page,$paginate=10,$like=[],$uid = null,$type =1){
        $UserCardModel = new UserCardModel();
        // 获取绑定列表
        $FamilyCardModel = new FamilyCardModel();
        // 用户身份证信息
        $IdentityCardModel= new IdentityCardModel();
        $did = $IdentityCardModel->where('uid',$uid)->value('did');
        $returnData = [
            'total'         =>  0,
            'per_page'      =>  $paginate,
            'current_page'  =>  0,
            'last_page'     =>  0,
            'data'          =>  []
        ];
        if(!$did) return $returnData;

        $list =$FamilyCardModel->where('puid',$uid)->where('type',999)->where('state',1)->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
            // 获取卡片产品信息
            $card_pro_info = (new CardProService())->m_card_pro_info($item['pid']);
            $card_pro_info = obj_to_arr($card_pro_info);
            $item['card_pro_info'] = $card_pro_info;
            // 获取卡片信息
            $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
            $card_info = obj_to_arr($card_info);
            $item['card_info'] = $card_info;
            // 获取卡片类型
            $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
            $card_type = obj_to_arr($card_type);
            $item['card_type'] = $card_type;
            // 获取用户关联卡片信息
            $card_user_info = (new CardUserModel())->where(['pid'=>$item['pid'],'uid'=>$item['puid'],'is_active'=>1])->find();
            if($card_user_info&&$card_user_info['valid_time']){
                $item['valid_time'] = $card_user_info['valid_time'];
            }
            $item['cu_id'] = $card_user_info['cu_id'];
            $item['is_read_rights'] = $card_user_info['is_read_rights'];
            // 持卡人
            $IdentityCardInfo = obj_to_arr((new IdentityCardModel())->where('did', $item['did'])->find());
            $item['identity_card_info'] = $IdentityCardInfo;
            // 叠加卡
            $item['append'] = [];
            if($card_type['id']==17){
                $append = obj_to_arr((new UserCardModel())
                    ->where('cu_id', $item['cu_id'])
                    ->whereOr('parent_cu_id', $item['cu_id'])
                    ->order('valid_time', 'asc')->select());
                foreach ($append as &$subItem){
                    $subItem['code']=(new CardProModel())->where('pid',$subItem['pid'])->value('code');
                    $subItem['name']=$IdentityCardInfo['name'];
                }
                $item['append'] = $append;
            }
        });
        return obj_to_arr($list);
    }
    // 失效权益卡片[自己]
    public function  s_myself_invalid_card_list($page=1,$paginate=10,$uid = null){
        if(empty($uid)) return false;
        // 用户卡片列表
        $UserCardModel = new UserCardModel();
        $list = $UserCardModel
            ->where('uid',$uid)
            ->where('parent_cu_id', 'NULL')
            ->where('valid_time','<',time())
            ->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
            // 获取卡片产品信息
            $card_pro_info = (new CardProService())->m_card_pro_info($item['pid']);
            $card_pro_info = obj_to_arr($card_pro_info);
            $item['card_pro_info'] = $card_pro_info;
            // 获取卡片信息
            $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
            $card_info = obj_to_arr($card_info);
            $item['card_info'] = $card_info;
            // 获取卡片类型
            $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
            $card_type = obj_to_arr($card_type);
            $item['card_type'] = $card_type;
        });


        return obj_to_arr($list);
    }

    // 失效权益卡片[家人]
    public function  s_myself_family_invalid_card_list($page=1,$paginate=10,$uid = null,$type){
        if(empty($uid)) return false;
        $UserServide = new WxUserService();
        // 查看用户是否实名认证
        $userDid = $UserServide->is_user_authentication($uid);
        if(!$userDid) json_err(-201,['该用户信息未认证,请先实名认证！']);
        // 获取家庭成员绑定关系
        $FamilyCardModel = new FamilyCardModel();
        $filterData = $FamilyCardModel->alias('a')->where('a.did',$userDid)->join('user_card b','a.pid = b.pid and b.uid =a.puid and b.valid_time <'.time());
        $list = $filterData->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
            // 获取卡片产品信息
            $card_pro_info = (new CardProService())->m_card_pro_info($item['pid']);
            $card_pro_info = obj_to_arr($card_pro_info);
            $item['card_pro_info'] = $card_pro_info;
            // 获取卡片信息
            $card_info = (new CardService())->getCardInfo($card_pro_info['cid']);
            $card_info = obj_to_arr($card_info);
            $item['card_info'] = $card_info;
            // 获取卡片类型
            $card_type = (new CardTypeService())->s_card_type_info($card_info['ct_id']);
            $card_type = obj_to_arr($card_type);
            $item['card_type'] = $card_type;
        });
        return obj_to_arr($list);
    }

    // 使用权益并填写资料
    public function apply_equity_info($data) {
        $CardEquityUserModel = new CardEquityUserModel();
        $CardEquityUserInfoModel = new CardEquityUserInfoModel();
        $UserCardModel = new UserCardModel();

//        $bind_card_info = obj_to_arr($UserCardModel->where(['uid' => $data['uid'], 'cu_id' => $data['cu_id'],])->find());
        $bind_card_info = obj_to_arr($UserCardModel->where(['cu_id' => $data['cu_id'],])->find());
        if(!$bind_card_info) json_err(-204,['卡片产品绑定信息,']);

        $card_pro_info = obj_to_arr((new CardProService())->m_card_pro_info($bind_card_info['pid']));
        if(!$card_pro_info) json_err(-204,['卡片产品信息,']);

        $card_info = obj_to_arr((new CardService())->getCardInfo($card_pro_info['cid']));
        if(!$card_info) json_err(-204,['卡片信息,']);
        if(!$card_info['eid'] || !in_array($data['eid'], explode(',', $card_info['eid']))) json_err(-210,['卡片无权益信息']);

        $equityInfo = obj_to_arr((new CardEquityModel())->where('state',1)->where('eid',$data['eid'])->find());
        if(!$equityInfo) json_err(-210,['卡片无权益信息']);

        $did = '';
        if(isset($data['did']) && !empty($data['did'])){
            $did = $data['did'];
        }else{
            $did = (new IdentityCardModel())->where('uid',$data['uid'])->value('did');
        }

        if((new CardEquityUserModel())->where([
            'cu_id'     => $data['cu_id'],
            'uid'       => $data['uid'],
            'eid'       => $data['eid'],
            'state'     => 0,
        ])->count() > 0){
            json_err(-210,['存在审核中的卡片权益信息，暂时无法申请']);
        }

        // 权益申请间隔判断
        if($card_info['equity_apply_interval_days'] and $equityInfo['equity_apply_interval'] == 1){
            $card_type = obj_to_arr((new CardTypeService())->s_card_type_info($card_info['ct_id']));

            $eidArr = obj_to_arr((new CardEquityModel())->field('eid')
                ->where('state',1)
                ->where('equity_apply_interval',1)
                ->where('eid','in', explode(',', $card_info['eid']))->select());
            $eidArr = array_column($eidArr, 'eid');

            $interval_days = $card_info['equity_apply_interval_days'];
            if($card_type['type']==2 and $card_type['id']!=16){
                // 家庭卡相同权益需要间隔
                if((new CardEquityUserModel())
                        ->where('cu_id',$data['cu_id'])
                        ->where('state','in', [0,1])
                        ->where('eid', $data['eid'])
                        ->whereTime('create_time', '>=', date('Y-m-d H:i:s', strtotime('-'.$interval_days.' days')))
                        ->count() > 0){
                    json_err(-210,['请等待前面权益完结'.$interval_days.'天后方可申请']);
                }
            }else {
                // 个人卡不同权益需要间隔
                if((new CardEquityUserModel())
                        ->where('cu_id',$data['cu_id'])
                        ->where('state','in', [0,1])
                        ->where('eid','in', $eidArr)
                        ->whereTime('create_time', '>=', date('Y-m-d H:i:s', strtotime('-'.$interval_days.' days')))
                        ->count() > 0){
                    json_err(-210,['请等待前面权益完结'.$interval_days.'天后方可申请']);
                }
            }
        }
//        $eidArr = obj_to_arr((new CardEquityModel())->field('eid')
//            ->where('state',1)
//            ->where('eid','in', explode(',', '46,47,48,49,50,51,52'))
//            ->where('eid','in', explode(',', $card_info['eid']))->select());
//        if(!empty($eidArr)){
//            $eidArr = array_column($eidArr, 'eid');
//            if((new CardEquityUserModel())
//                    ->where('cu_id',$data['cu_id'])
//                    ->where('state',1)
//                    ->where('eid','in',$eidArr)
//                    ->whereTime('create_time', '>=', date('Y-m-d H:i:s', strtotime('-20 days')))
//                    ->count() > 0){
//                json_err(-210,['请等待前面权益完结20天后方可申请']);
//            }
//            if((new CardEquityUserModel())
//                    ->where('cu_id',$data['cu_id'])
//                    ->where('state',0)
//                    ->where('eid','in',$eidArr)
//                    ->count() > 0){
//                json_err(-210,['请等待前面权益完结20天后方可申请']);
//            }
//        }

        if(isset($equityInfo['frequency_period'])){
            $creation_time = strtotime($bind_card_info['creation_time']);
            if(isset($equityInfo['waiting_period'])){
                $creation_time = strtotime('+'.$equityInfo['waiting_period'].' days',$creation_time);
            }
            $i=1000;
            while($i>0){
                $begin=$creation_time;
                $end=strtotime('+'.$equityInfo['frequency_period'],$creation_time);
                if(time()>$begin&&time()<$end){
                    $count = (new CardEquityUserModel())->where(['cu_id' => $data['cu_id'], 'did' => $did])
                        ->where('create_time','>=',date("Y-m-d H:i:s", $begin))
                        ->where('create_time','<',date("Y-m-d H:i:s", $end))
                        ->where('state','<',2)->count();
                    if(((int)$equityInfo['frequency']) <= $count){
                        json_err(-210,['可用权益次数不足']);
                    }else{
                        break;
                    }
                }else if(time()<=$begin){
                    break;
                }else{
                    $creation_time=$end;
                }
                $i--;
            }
        }else{
            $count = (new CardEquityUserModel())->where(['uid' => $data['uid'], 'cu_id' => $data['cu_id'],])->count();
            if(((int)$equityInfo['frequency']) <= $count) json_err(-210,['可用权益次数不足']);
        }

        if(isset($equityInfo['frequency_all'])){
            $count = (new CardEquityUserModel())->where(['uid' => $data['uid'], 'cu_id' => $data['cu_id'], 'state' => 1,])->count();
            if(((int)$equityInfo['frequency_all']) <= $count) json_err(-210,['可用权益已达到总次数']);
        }

        if($equityInfo['waiting_period'] > 0){ // 等待期
            date_default_timezone_set("PRC");
            $addDays = sprintf("+%d day", $equityInfo['waiting_period']);
            $creationTime = strtotime($bind_card_info['creation_time']);
            $lastWaitingTime = strtotime(date("Y-m-d",strtotime($addDays, $creationTime)));
            if(time()<$lastWaitingTime) json_err(-210,['等待期还未通过，请等待']);
        }

        $cardEquityUserModelData = [
            'cu_id'     => $data['cu_id'],
            'cid'       => $card_pro_info['cid'],
            'uid'       => $data['uid'],
            'eid'       => $data['eid'],
            'did'       => $did,
            'frequency' => 1,
        ];
        $orderNo = sprintf("T%s%d",date("YmdHis", time()),getRandNumber(0,9,2));
        $cardEquityUserModelData['state'] = 0;
        $cardEquityUserModelData['order_no'] = $orderNo;
        $ue_id = (new CardEquityUserModel())->insertGetId($cardEquityUserModelData);

        $res = (new CardEquityUserInfoModel())->save([
            'ue_id'         => $ue_id,
            'uid'           => $data['uid'],
            'name'          => $data['name'],
            'id_card'       => $data['id_card'],
            'mobile'        => $data['mobile'],
            'remarks'       => $data['remarks'],
            'upload_data'   => $data['upload_data'],
	        'ct_id'         => $card_info['ct_id'],
        ]);

        if($res) return true;
        return false;
    }

    // 阅读权益告知条款并提交签名
    public function read_card_rights($cuid,$uid,$img){
        $res = (new UserCardModel())->save([
            'is_read_rights'  =>  1,
            'sign_img'  =>  $img,
        ],[
            'uid'   =>  $uid,
            'cu_id' =>  $cuid,
        ]);
        if($res) return true;
        return false;
    }

    // 服务列表，权益申请列表
    public function get_apply_equity_info($data) {
        $CardEquityUserModel = new CardEquityUserModel();
        $CardEquityUserModel->alias('a')->where(['a.uid'=>$data['uid']]);
        $CardEquityUserModel->join('card_equity b', 'a.eid=b.eid')->field('a.*,b.title');
        if(isset($data['state'])&&strlen($data['state'])){
            $CardEquityUserModel->where(['a.state'=>$data['state'],]);
        }
        $get_apply_equity_infos = $CardEquityUserModel->select();
        $get_apply_equity_infos = obj_to_arr($get_apply_equity_infos);
        return $get_apply_equity_infos;
    }

    // 服务详情
    public function get_apply_equity_info_detail($data) {
        $CardEquityUserModel = new CardEquityUserModel();
        $CardEquityUserModel->alias('a')->where(['a.ue_id' => $data['ue_id'],'a.uid'=>$data['uid']]);
        $CardEquityUserModel->join('card_equity b', 'a.eid=b.eid')
            ->join('user_card uc','a.cu_id=uc.cu_id')
            ->join('card_product cp','cp.pid=uc.pid')
            ->join('identity_card ic','ic.uid=a.uid')
            ->field('a.*,b.title,cp.code,ic.name,ic.mobile,ic.id_card');
        $get_apply_equity_info_detail = $CardEquityUserModel->find();
        $get_apply_equity_info_detail = obj_to_arr($get_apply_equity_info_detail);
        return $get_apply_equity_info_detail;
    }

    // 获取省市区
    public function get_area_region($p_r_id,$level) {
        $AreaRegion = (new AreaRegionModel())->where(['p_r_id'=>$p_r_id,'level'=>$level])->select();
        return obj_to_arr($AreaRegion);
    }

    // 获取医院
    public function hospital($data){
        $HospitalModel = null;
        if(!isset($data['type']) or $data['type']==0){
            $HospitalModel = new HospitalModel();
        }else{
            $HospitalModel = new Hospital2Model();
        }
        if(!empty($data['search'])){
            $HospitalModel->where('hospital', 'like', "%{$data['search']}%");
        }
        return obj_to_arr($HospitalModel->paginate($data['page_number'],false,['page'=>$data['page']]));
    }

    // 权益物流列表
    public function get_apply_equity_express($data) {
        $CardEquityUserModel = new CardEquityUserModel();
        $CardEquityUserModel->alias('a')->where(['a.uid'=>$data['uid']]);
        $CardEquityUserModel->join('card_equity b', 'a.eid=b.eid')->field('a.*,b.title');
        $CardEquityUserModel->join('card_equity_express cee','cee.ue_id=a.ue_id');
        if(isset($data['state'])&&strlen($data['state'])){
            $CardEquityUserModel->where(['a.state'=>$data['state'],]);
        }
        $get_apply_equity_infos = $CardEquityUserModel->select();
        $get_apply_equity_infos = obj_to_arr($get_apply_equity_infos);
        return $get_apply_equity_infos;
    }

    // 权益物流详情
    public function get_apply_equity_express_detail($data) {
        $CardEquityUserModel = new CardEquityUserModel();
        $CardEquityUserModel->alias('a')->where(['a.ue_id' => $data['ue_id'],'a.uid'=>$data['uid']]);
        $CardEquityUserModel->join('card_equity b', 'a.eid=b.eid')
            ->join('user_card uc','a.cu_id=uc.cu_id')
            ->join('card_product cp','cp.pid=uc.pid')
            ->join('identity_card ic','ic.uid=a.uid')
            ->join('card_equity_express cee','cee.ue_id=a.ue_id')
            ->field('a.*,b.title,cp.code,ic.name,ic.mobile,ic.id_card,cee.logistic_code,cee.shipper_name,cee.recipient_name,cee.mobile as recipient_mobile,cee.address as recipient_address,cee.response_data');
        $get_apply_equity_info_detail = $CardEquityUserModel->find();
        $get_apply_equity_info_detail = obj_to_arr($get_apply_equity_info_detail);
        return $get_apply_equity_info_detail;
    }
}

